package com.raymond.http.netty;

import com.raymond.http.HttpNettyClient;
import com.raymond.http.MessageManages;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.pool.FixedChannelPool;
import io.netty.channel.pool.SimpleChannelPool;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.concurrent.TimeoutException;

/**
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-12-11 18:13
 */
@Slf4j
public class DefaultHttpClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

    private MessageManages messageManages;

    private HttpFixedChannelPool fixedChannelPool;

    public DefaultHttpClientHandler(HttpFixedChannelPool fixedChannelPool) {
        this.fixedChannelPool = fixedChannelPool;
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
//        log.info("响应刷出数据ID:{},数据：{}", ctx.channel().id(), msg.content().toString(Charset.defaultCharset()));
        setSuccess(msg);
        fixedChannelPool.release(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (!isResp()) {
            log.debug("ctx.channel():{}", ctx.channel());
            messageManages.getPromise().setFailure(new TimeoutException("响应超时关闭连接"));
        }
        fixedChannelPool.close(ctx.channel());
        super.channelInactive(ctx);
    }

    public void setMessageManages(MessageManages messageManages) {
        this.messageManages = messageManages;
    }

    private void setSuccess(FullHttpResponse msg) {
        messageManages.getPromise().setSuccess(msg);
        this.messageManages = null;
    }

    private synchronized boolean isResp() {
        return this.messageManages == null;
    }
}
